const app = new getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    prompt: '',
    user_info: {},
    email: '',
    new_email: '',
    code: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;

    app.sendRequest({
      url: "api.php?s=member/getMemberDetail",
      data: {},
      method: "POST",
      success: function (res) {
        let code = res.code;
        if (code == 0) {
          that.setData({
            user_info: res.data.user_info,
            email: res.data.user_info.user_email,
            new_email: res.data.user_info.user_email,
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },

  /**
   * 输入邮箱
   */
  inputEmail: function(e){
    let that = this;
    let email = e.detail.value;
    
    that.setData({
      new_email: email
    })
  },

  saveEmail: function(e){
    let that = this;
    let email = that.data.email;
    let new_email = that.data.new_email;

    if (new_email == '') {
      app.showBox(that, '邮箱不可为空');
      return false;
    }

    let myreg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
    if (new_email.length != 11 || !myreg.test(new_email)) {
      app.showBox(that, '邮箱格式不正确');
      return false;
    }

    if (new_email == email) {
      app.showBox(that, '与原邮箱一致，无需修改');
      return false;
    }

    //验证手机号
    app.sendRequest({
      url: "api.php?s=login/email",
      data: {
        email: new_email
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        let code = res.code;
        let data = res.data;
        if (code == 0) {
          if (data == true) {
            app.showBox(that, '该邮箱已存在');
            return false;
          } else {
            that.save(that, new_email);
          }
        }
      }
    });
  },

  /**
   * 保存
   */
  save: function (that, email) {

    app.sendRequest({
      url: "api.php?s=member/modifyemail",
      data: {
        email: email
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        let code = res.code;
        let data = res.data;
        if (code == 0) {
          if (data > 0) {
            wx.navigateBack({
              delta: 1
            })
          } else {
            app.showBox(that, '操作失败');
            return false;
          }
        }
      }
    });
  }
})